package org.mat.admin.sys.security.interceptor;

import org.mat.admin.sys.api.model.LoginUser;
import org.mat.admin.sys.security.SecurityContextHolder;
import org.mat.admin.sys.security.auth.AuthUtil;
import org.mat.admin.sys.util.SecurityConstants;
import org.mat.admin.sys.util.SecurityUtils;
import org.mat.admin.sys.util.ServletUtils;
import org.mat.admin.sys.util.StringUtils;
import org.mat.framework.core.context.RequestContext;
import org.mat.framework.core.context.RequestContextUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 *
 * @author ruoyi
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }


        String userId = ServletUtils.getHeader(request, SecurityConstants.DETAILS_USER_ID);
        SecurityContextHolder.setUserId(userId);
        String userName = ServletUtils.getHeader(request, SecurityConstants.DETAILS_USERNAME);
        SecurityContextHolder.setUserName(userName);
        String user = ServletUtils.getHeader(request, SecurityConstants.USER_KEY);
        SecurityContextHolder.setUserKey(user);

        RequestContext requestContext = RequestContextUtils.get();
        if (requestContext == null){
            requestContext = RequestContext.builder().build();
        }
        HashMap<String, String> data = new HashMap<>();
        data.put(SecurityConstants.DETAILS_USER_ID, userId);
        data.put(SecurityConstants.DETAILS_USERNAME, userName);
        data.put(SecurityConstants.USER_KEY, user);
        requestContext.setData(data);
        RequestContextUtils.set(requestContext);

        String token = SecurityUtils.getToken();
        if (StringUtils.isNotEmpty(token)) {
            LoginUser loginUser = AuthUtil.getLoginUser(token);
            if (StringUtils.isNotNull(loginUser)) {
                AuthUtil.verifyLoginUserExpire(loginUser);
                SecurityContextHolder.set(SecurityConstants.LOGIN_USER, loginUser);
            }
        }


        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        SecurityContextHolder.remove();
    }
}
